package logger

import (
	"net/url"
	"sync"

	"go.uber.org/zap"
)

// logger_sinks: 管理注册的sink并缓存
var sinkMgmt *SinkMgmt

type (
	SinkMgmt struct {
		mu    sync.Mutex
		sinks map[string]zap.Sink
	}

	NewSinkFunc func(url *url.URL) (zap.Sink, error)
)

func init() {
	sinkMgmt = &SinkMgmt{sinks: make(map[string]zap.Sink, 10)}
}

// 若sink.URL已注册, 则会直接复用
// e.g: OutputPath==ErrorOutputPath
func NewCacheSink(schema string, fn NewSinkFunc) NewSinkFunc {
	sinkMgmt.mu.Lock()
	defer sinkMgmt.mu.Unlock()

	return func(url *url.URL) (zap.Sink, error) {
		if sink, find := sinkMgmt.sinks[url.String()]; find {
			return sink, nil
		}
		sink, err := fn(url)
		if err != nil {
			return sink, err
		}
		sinkMgmt.sinks[url.String()] = sink
		return sink, nil
	}
}

func CloseSink(url string) error {
	sinkMgmt.mu.Lock()
	defer sinkMgmt.mu.Unlock()

	if sink, find := sinkMgmt.sinks[url]; find {
		delete(sinkMgmt.sinks, url)
		return sink.Close()
	}
	return nil
}
